﻿using ALMDDD.Domain.Model;
using ALMDDD.Infrastructure.Mappings;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ALMDDD.Infrastructure.Context
{
    /// <summary>
    /// ALM连接数据库上线文对象
    /// </summary>
    public class ALMContext : DbContext
    {

        public static readonly LoggerFactory MyLoggerFactory = new LoggerFactory(new[] {
            new ConsoleLoggerProvider((category, level)  => category == DbLoggerCategory.Database.Command.Name&& level == LogLevel.Information, true)
        });
        public ALMContext() { }
        public virtual DbSet<Sys_User> sys_role { get; set; }
        public virtual DbSet<Sys_Role> sys_user { get; set; }
        public virtual DbSet<SysUserRole> sys_user_role { get; set; }
        /// <summary>
        ///
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema(null);

            modelBuilder.ApplyConfiguration(new SysUserMap());
            modelBuilder.ApplyConfiguration(new SysUserRoleMap());
            modelBuilder.ApplyConfiguration(new SysRoleMap());
            base.OnModelCreating(modelBuilder);
        }
        /// <summary>
        /// 重写连接数据库
        /// </summary>
        /// <param name="dbContextOptionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
        {
            //从 appsetting.json 中获取配置信息
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            // 定义要使用的数据库
            dbContextOptionsBuilder.UseSqlServer(config.GetConnectionString("DefaultConnection"));
            //延迟加载
            dbContextOptionsBuilder.UseLazyLoadingProxies().UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            dbContextOptionsBuilder.UseLoggerFactory(MyLoggerFactory);//控制台打印日志
            base.OnConfiguring(dbContextOptionsBuilder);

        }

    }
}
